var fetch = require('node-fetch');
var host = require('./conf.js').host;
var Request = function(option){
    option = option || {};
    var url = host+option.url; // address
    var type = option.type || 'POST'; //request type
    var data = option.data || {}; // request data
    var success = option.success;   //success callback
    var error = option.error;

    fetch(url,{
        mode:'cors',
        method:type,
        headers:{
            'Accept': 'application/json',
            'content-type': 'application/json'
        },
        body:JSON.stringify(data)
    })
    .then(function(response){
        response.json()
        .then(function(json){
            var dateSuccess = new Date;
            console.log('receive data from '+url);
            console.log(json);
            console.log('it takes '+(dateSuccess-date)+' ms');
            var ifSucces = json.success;
            if(ifSucces){
                success(json);
            }else{
                error(json);
            }
        })
        .catch(function(err){
            error&&error({success:false,replyText:'data\'s format is unexpect!'});
        })
    })
    .catch(function(err){
        error&&error({success:false,replyText:'net work error'});
    });
    
    var date = new Date;
    console.log(date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds()+' start to fetch data! ');
    console.log('Fetching data from '+url);
    console.log('request data:');
    console.log(data);
}

module.exports = Request;
